package logic

import (
	"context"
	"fmt"
	"strings"

	"server_1.0/service/student/internal/svc"
	"server_1.0/service/student/student"
	"server_1.0/util"

	"github.com/zeromicro/go-zero/core/logx"
)

type QueryNameLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewQueryNameLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryNameLogic {
	return &QueryNameLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *QueryNameLogic) QueryName(in *student.QueryNameReq) (*student.QReps, error) {
	pre := "%"
	rstr := strings.Split(in.Name, "")
	pstr := strings.Join(rstr, pre)
	str := fmt.Sprintf("%s%s%s", pre, pstr, pre)
	stu, err := l.svcCtx.StudentModel.FindOneName(l.ctx, str)
	code := util.Success
	usersHandle := make([]*student.Reps, 0)
	count := 0
	if err != nil {
		code = util.NoFoundError
		usersHandle = append(
			usersHandle,
			&student.Reps{
				Code: int64(code),
				Name: in.Name,
			})
		count += 1
		return &student.QReps{
			Count: int64(count),
			QRs:   usersHandle,
		}, nil
	} else {
		code = util.Success
		for _, item := range stu {
			usersHandle = append(
				usersHandle,
				&student.Reps{
					Code:     int64(code),
					No:       item.Sno,
					Name:     item.Sname,
					Sex:      item.Ssex,
					Age:      item.Sage,
					Password: item.Spwd,
				})
			count += 1
		}

		return &student.QReps{
			Count: int64(count),
			QRs:   usersHandle,
		}, nil
	}
}
